import React, { useState, useRef, useEffect } from 'react';
import ConfirmDialog from './ConfirmDialog'; // 引入ConfirmDialog组件

interface ItemType {
    id: string;
    title: string;
    completed: boolean;
    create_time: number;
    update_time: number;
    delete_time: number;
}

interface IProps {
    currentTab: string;
    dataList: ItemType[];
    checkTodoItem: (itemId: string) => void;
    updateTodoItem: (itemId: string, title: string) => void;
    deleteTodoItem: (itemId: string) => void;
    handleUpdateCounts: () => void;
}

const MainBody: React.FC<IProps> = ({ currentTab, dataList, checkTodoItem, updateTodoItem, deleteTodoItem, handleUpdateCounts }) => {
    const [editingItemId, setEditingItemId] = useState<string | null>(null);
    const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); // 添加状态来控制删除确认对话框的显示
    const [itemToDelete, setItemToDelete] = useState<ItemType | null>(null); // 添加状态来存储要删除的项目
    const inputRefs = useRef<{ [key: string]: HTMLInputElement }>({});

    // 根据数据状态筛选数据
    const [filteredDataList, setFilteredDataList] = useState<ItemType[]>(dataList);

    useEffect(() => {
        // 根据 currentTab 筛选数据
        const filteredList = dataList.filter(item => {
            if (currentTab === 'all') {
                return true;
            } else if (currentTab === 'pending') {
                return !item.completed;
            } else if (currentTab === 'completed') {
                return item.completed;
            }
            return false;
        });

        setFilteredDataList(filteredList);

        // 计算条数
        handleUpdateCounts();
    }, [dataList, currentTab, handleUpdateCounts]);

    useEffect(() => {
        console.log("props:::::", { dataList, checkTodoItem, updateTodoItem });
        console.warn("MainBody 生命周期：mount");
        return () => {
            console.warn("MainBody 生命周期：unmount");
        };
    }, [dataList, checkTodoItem, updateTodoItem, editingItemId]);

    useEffect(() => {
        console.warn("MainBody 生命周期：update");
    });

    /**
     * item双击编辑
     * @param itemId
     */
    const handleDoubleClick = (itemId: string) => {
        console.log("handleDoubleClick", itemId);
        setEditingItemId(itemId);
    };

    // 双击时自动将鼠标 focus 到当前要编辑的输入框
    useEffect(() => {
        if (editingItemId) {
            const inputElement = inputRefs.current[editingItemId];
            if (inputElement) {
                inputElement.focus();
                inputElement.value = inputElement.value.trim();
                //inputElement.select();
            }
        }
    }, [editingItemId]);

    /**
     * item编辑失去焦点提交
     * @param itemId
     * @param event
     */
    const handleBlur = (itemId: string, event: React.FocusEvent<HTMLInputElement>) => {
        const newTitle = event.currentTarget.value.trim();
        updateTodoItem(itemId, newTitle);
        setEditingItemId(null);
    };

    /**
     * item编辑回车提交
     * @param itemId
     * @param event
     */
    const handleKeyUp = (itemId: string, event: React.KeyboardEvent<HTMLInputElement>) => {
        if (event.key === 'Enter') {
            event.preventDefault();
            const newTitle = event.currentTarget.value.trim();
            updateTodoItem(itemId, newTitle);
            setEditingItemId(null);
        }
    };

    /**
     * 复选框勾选状态改变事件
     * @param itemId
     */
    const handleCheckboxChange = (itemId: string) => {
        checkTodoItem(itemId);
    };

    // 添加处理删除按钮点击的函数
    const handleDeleteBtnClick = (item: ItemType) => {
        setItemToDelete(item);
        setShowDeleteConfirm(true);
    };

    // 添加处理确认删除的函数
    const handleConfirmDelete = () => {
        if (itemToDelete) {
            deleteTodoItem(itemToDelete.id); // 调用 deleteTodoItem 方法
        }
        setShowDeleteConfirm(false);
    };

    // 添加处理取消删除的函数
    const handleCancelDelete = () => {
        setShowDeleteConfirm(false);
    };

    /**
     * 列表为空时提示文字获取
     */
    const getEmptyListText = () => {
        switch (currentTab) {
            case 'pending':
                return '暂无待完成数据';
            case 'completed':
                return '暂无已完成数据';
            default:
                return '暂无数据，请添加';
        }
    };

    return (
        <div className="main-body">
            <ul className="todo-list">
                {filteredDataList.map((item: ItemType) => (
                    <li
                        className={['item', item.completed? 'completed' : '', item.id === editingItemId? 'editing' : ''].join(' ').trim()}
                        key={item.id}
                    >
                        <div className="view">
                            <input
                                type="checkbox"
                                className="toggle"
                                checked={item.completed}
                                onChange={() => handleCheckboxChange(item.id)}
                            />
                            <label
                                className={`check-icon ${item.completed? 'completed' : ''}`}
                                onDoubleClick={() =>!item.completed && handleDoubleClick(item.id)}
                            >
                                {item.title}
                            </label>
                            <button className="delete-btn" onClick={() => handleDeleteBtnClick(item)} />
                        </div>
                        <div className="edit">
                            <input
                                ref={(ref) => (inputRefs.current[item.id] = ref!)}
                                type="text"
                                defaultValue={item.title}
                                onBlur={(e) => handleBlur(item.id, e)}
                                onKeyUp={(e) => handleKeyUp(item.id, e)}
                            />
                        </div>
                    </li>
                ))}
            </ul>
            {filteredDataList.length === 0 && (
                <div className="list-empty">
                    <span>{getEmptyListText()}</span>
                </div>
            )}
            {showDeleteConfirm && ( // 显示删除确认对话框
                <ConfirmDialog
                    isOpen={showDeleteConfirm}
                    title="确认删除?"
                    message={`确定要删除 "${itemToDelete?.title}" 吗？`}
                    onConfirm={handleConfirmDelete}
                    onCancel={handleCancelDelete}
                />
            )}
        </div>
    );
};

export default MainBody;